import threading
import time
import paho.mqtt.client as mqtt

from mqttApi import protomessage_pb2 # 直接import会找不到module



class MqttCtrl():
    """
    作为基本的mqtt基本管理类
    """
    HOST = "192.168.0.118"
    PORT = 1883
    client=None
    messageFlag = False
    message = ""

    def __init__(self):
        print("mqtt初始化")

    def mqttManage(self, HOST="123.249.33.130", PORT=1883):
        try:
            self.client = mqtt.Client()
            self.client.username_pw_set(username="tianxiaohuaPC")
            self.client.connect(HOST, PORT, 60)
            self.client.loop_start()
            while True:
                time.sleep(10)
                print("...")
        except:
            print("MQTT:mqttManage error")

    # 设备上线后会发布topic为手机号加设备识别编号的消息，网站开始需要订阅这个消息并作出反应。
    def on_message_deviceManage(self, lient, userdata, message):
        # 回调函数
        #
        # print("！"+msg.topic + " " + ":" + str(message.payload))
        test = protomessage_pb2.ILampStateHeart()
        test.ParseFromString(message.payload)
        print(test.user_ID)
        print(test.DeviceType)
        print(test.DeviceID)
        print(test.DeviceSwitchState)
        print(test.Luminance)
        print(test.Color)

    def deviceManage(self, Topic = "1381234432110"):
        print("订阅+"+Topic)
        self.client.subscribe(Topic, 1)
        self.client.on_message = self.on_message_deviceManage  # 消息到来处理函数 回调函数


    def mqttInit(self):
        # 创建线程
        try:
            thread = threading.Thread(target=self.mqttManage)
            thread.start()
            time.sleep(1)
        except:
            print("Error: unable to start thread")
        self.deviceManage(Topic = "1381234432110")



    def mqttPub(self,Topic="test", payload='{"version":1.0.0}'):
        self.client.publish(Topic, payload, 2)  # 发布一个主题为'chat',内容为json的信息

    # 消息处理函数
    def on_message_come(self,lient, userdata, msg):
        print(msg.topic + " " + ":" + str(msg.payload))
        self.messageFlag=True
        self.message=msg.topic + " " + ":" + str(msg.payload)

    def mqttSub(self,Topic="test"):
        """
        Topic：主体内容
        """
        self.client.subscribe(Topic, 1)
        self.client.on_message = self.on_message_come  # 消息到来处理函数


    def pubMessage(HOST="192.168.0.119", PORT=1883, Topic="test", payload='{"version":1.0.0}'):
        """
        HOST:要连接的目标mqtt服务器的IP
        POST：目标服务器的端口
        Topic：主体内容
        payload：消息内容
        MQTT传输的消息分为：主题（Topic）和负载（payload）两部分
        """
        global sandFlag
        client = mqtt.Client()
        client.connect(HOST, PORT, 60)
        client.loop_start()
        client.publish(Topic, payload, 2)  # 发布一个主题为'chat',内容为‘hello liefyuan’的信息
        while True:
            time.sleep(0.1)
            break



    def subMessage(HOST="192.168.0.119", PORT=1883, Topic="U17614066424D00000001"):
        payload = '{"version":1.0.0}'
        return payload


def mqttMain():
    while True:
        time.sleep(0.3)
        print("go go go!")

mqttCtrl = MqttCtrl()

if __name__ == '__main__':
    pass
